<!-- B页面 -->
<template>
	<view class="img_page">
		<view class="closeImg">
			<image @click="close" src="@/static/Myimg/cha.png" mode=""></image>
		</view>
		<image @click="close" class="touxiang" :src="imgurl" mode="aspectFill"></image>
		<view @click="go_phono" class="but">
			<text>更换背景图</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgurl: [] // 初始化为空字符串
			};
		},
		methods: {
			close() {
				uni.navigateBack({
					delta: 1
				})
			},
			go_phono() {
				uni.chooseImage({
					count: 1,
					sourceType: ['camera'],
					success: (res) => {
						console.log(res);
						const file = res.tempFiles[0];
						const userId = uni.getStorageSync("id")
						const formData = new FormData();
						formData.append('file', file);
						formData.append('userId', userId);
						const token = uni.getStorageSync("Authorization");
						const fileType = file.type.startsWith('image') ? 'image' : file.type.startsWith(
							'video') ? 'video' : 'unknown';
						console.log(fileType);
						formData.append('bgUrl', fileType);
						const headers = new Headers();
						headers.append('Authorization', token);
						const requestOptions = {
							method: 'POST',
							headers: headers,
							body: formData // FormData object
						};
						
						// Send FormData to the server
						fetch('http://localhost:8088/userProfileEditor/upUserBgUrl', requestOptions)
							.then(response => {
								if (!response.ok) {
									throw new Error('Upload failed');
								}
								return response
									.json(); // If the server returns JSON data, process the response
							})
							.then(data => {
								console.log('Upload successful', data);
								if (data.code == 200) {
									this.imgurl = data.result.bgUrl; // Update imgurl with the new URL
								}
							})
							.catch(error => {
								console.error('Upload failed', error);
							});
					},
					fail: (err) => {
						console.error('拍照失败', err);
					}
				});
			}
		},
		onLoad(e) {
			// 接收传递的图片路径
			// this.imgurl = decodeURIComponent(e.imgUrl);
			this.imgurl = decodeURIComponent(e.imgUrl);
			console.log(e);
		}
	};
</script>

<style scoped>
	page {
		background-color: #000;
		color: #fff;
	}

	.img_page {
		display: flex;
		flex-wrap: wrap;
		width: 100%;
	}

	.closeImg {
		width: 100%;
		height: 80rpx;
		margin-top: 100rpx;
	}

	.closeImg image {
		width: 70rpx;
		height: 70rpx;
		margin-left: 15rpx;
	}

	.touxiang {
		width: 100%;
		height: 500rpx;
		margin-top: 290rpx;
	}

	.but {
		width: 240rpx;
		height: 80rpx;
		border-radius: 50rpx;
		background-color: rgb(34, 34, 34);
		text-align: center;
		line-height: 80rpx;
		font-size: 30rpx;
		margin-top: 200rpx;
		margin-left: 280rpx;
	}
</style>